// Copyright (c) 2011 SameGoal LLC.
// All Rights Reserved.
// Author: Andy Hochhaus <ahochhaus@samegoal.com>

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "net/http/server/comet/session_manager.h"

#include <glog/logging.h>

#include <map>
#include <string>
#include <vector>

#include "base/init.h"
#include "net/http/server/comet/session.h"

namespace sg {
namespace net {
namespace http {
namespace server {
namespace comet {

SessionManager::SessionMap *SessionManager::session_map_ = NULL;
std::mutex *SessionManager::mutex_ = NULL;

SessionManager::SessionRefCntPtr SessionManager::New(CometServer *server) {
  std::lock_guard<std::mutex> lock(*mutex_);
  Session *session = new Session(server);
  (*session_map_)[session->GetSid()].reset(session);
  return (*session_map_)[session->GetSid()];
}

SessionManager::SessionRefCntPtr SessionManager::GetSession(
    const std::string &sid) {
  std::lock_guard<std::mutex> lock(*mutex_);
  if (session_map_->find(sid) != session_map_->end()) {
    return (*session_map_)[sid];
  }
  return SessionRefCntPtr();
}

void SessionManager::Remove(const std::string &sid) {
  std::lock_guard<std::mutex> lock(*mutex_);
  session_map_->erase(sid);
}

void SessionManager::Terminate() {
  std::lock_guard<std::mutex> lock(*mutex_);
  while (!session_map_->empty()) {
    (*session_map_->begin()->second).Stop();
  }
}

}  // namespace comet
}  // namespace server
}  // namespace http
}  // namespace net
}  // namespace sg

REGISTER_MODULE_INITIALIZER(
    session_manager_initializer, {
      sg::net::http::server::comet::SessionManager::session_map_ =
          new sg::net::http::server::comet::SessionManager::SessionMap;
      sg::net::http::server::comet::SessionManager::mutex_ = new std::mutex;
    })
